<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useUserStore } from '@/stores'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star, ChatDotRound, More, Delete } from '@element-plus/icons-vue'
import { getCommentList, addComment, likeComment, deleteComment } from '@/api/discuss'

const userStore = useUserStore()

const props = defineProps({
  discussionId: {
    type: String,
    required: true
  },
  discussionTitle: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['comment-added', 'comment-deleted'])

// 响应式数据
const commentList = ref([])
const loading = ref(false)
const replyLoading = ref(false)
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 评论表单
const commentForm = reactive({
  content: '',
  parentCommentId: null
})

// 回复框状态
const replyStates = reactive({})

// 获取评论列表
const fetchComments = async () => {
  loading.value = true
  try {
    const response = await getCommentList({
      discussionId: props.discussionId,
      page: pagination.page,
      pageSize: pagination.pageSize
    })
    
    if (response.data.code === '0000') {
      commentList.value = response.data.data.list || []
      pagination.total = response.data.data.pagination?.total || 0
      
      // 初始化回复状态
      commentList.value.forEach(comment => {
        if (!replyStates[comment.id]) {
          replyStates[comment.id] = {
            visible: false,
            content: '',
            loading: false
          }
        }
        
        // 为每个回复也初始化状态
        if (comment.replies) {
          comment.replies.forEach(reply => {
            if (!replyStates[reply.id]) {
              replyStates[reply.id] = {
                visible: false,
                content: '',
                loading: false
              }
            }
          })
        }
      })
    } else {
      ElMessage.error(response.data.msg || '获取评论失败')
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  } finally {
    loading.value = false
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentForm.content.trim()) {
    ElMessage.error('请输入评论内容')
    return
  }
  
  if (commentForm.content.length > 1000) {
    ElMessage.error('评论内容不能超过1000个字符')
    return
  }
  
  try {
    const response = await addComment({
      discussionId: props.discussionId,
      content: commentForm.content.trim(),
      parentCommentId: commentForm.parentCommentId
    })
    
    if (response.data.code === '0000') {
      ElMessage.success(commentForm.parentCommentId ? '回复成功' : '评论成功')
      commentForm.content = ''
      commentForm.parentCommentId = null
      
      // 重置所有回复框状态
      Object.keys(replyStates).forEach(key => {
        replyStates[key].visible = false
        replyStates[key].content = ''
      })
      
      // 重新获取评论列表
      await fetchComments()
      emit('comment-added')
    } else {
      ElMessage.error(response.data.msg || '评论失败')
    }
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('评论失败')
  }
}

// 提交回复
const submitReply = async (commentId) => {
  const replyState = replyStates[commentId]
  if (!replyState.content.trim()) {
    ElMessage.error('请输入回复内容')
    return
  }
  
  replyState.loading = true
  try {
    const response = await addComment({
      discussionId: props.discussionId,
      content: replyState.content.trim(),
      parentCommentId: commentId
    })
    
    if (response.data.code === '0000') {
      ElMessage.success('回复成功')
      replyState.visible = false
      replyState.content = ''
      
      // 重新获取评论列表
      await fetchComments()
      emit('comment-added')
    } else {
      ElMessage.error(response.data.msg || '回复失败')
    }
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败')
  } finally {
    replyState.loading = false
  }
}

// 点赞评论
const handleLikeComment = async (comment) => {
  try {
    const response = await likeComment({ commentId: comment.id })
    if (response.data.code === '0000') {
      // 更新本地数据
      comment.likes = response.data.data.likes
      ElMessage.success('点赞成功')
    } else {
      ElMessage.error(response.data.msg || '点赞失败')
    }
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('点赞失败')
  }
}

// 删除评论
const handleDeleteComment = async (comment) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteComment({ commentId: comment.id })
    if (response.data.code === '0000') {
      ElMessage.success('删除成功')
      await fetchComments()
      emit('comment-deleted')
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 显示/隐藏回复框
const toggleReply = (commentId) => {
  if (!replyStates[commentId]) {
    replyStates[commentId] = {
      visible: false,
      content: '',
      loading: false
    }
  }
  replyStates[commentId].visible = !replyStates[commentId].visible
  replyStates[commentId].content = ''
  
  // 关闭其他回复框
  Object.keys(replyStates).forEach(key => {
    if (key !== commentId) {
      replyStates[key].visible = false
    }
  })
  
  // 滚动到回复框
  nextTick(() => {
    if (replyStates[commentId].visible) {
      const replyForm = document.getElementById(`reply-form-${commentId}`)
      if (replyForm) {
        replyForm.scrollIntoView({ behavior: 'smooth', block: 'center' })
      }
    }
  })
}

// 检查用户是否有权限删除评论
const canDeleteComment = (comment) => {
  return comment.author?.id === userStore.user?.id
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '未知时间'
  
  const date = new Date(timeString)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 计算评论总数（包括回复）
const totalComments = computed(() => {
  let count = commentList.value.length
  commentList.value.forEach(comment => {
    count += comment.replies ? comment.replies.length : 0
  })
  return count
})

// 分页处理
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.page = 1
  fetchComments()
}

const handleCurrentChange = (newPage) => {
  pagination.page = newPage
  fetchComments()
}

// 初始化
onMounted(() => {
  fetchComments()
})

// 暴露方法供父组件调用
defineExpose({
  refreshComments: fetchComments
})
</script>

<template>
  <div class="comment-section">
    <!-- 评论统计 -->
    <div class="comment-header">
      <h3>评论 ({{ totalComments }})</h3>
    </div>

    <!-- 发表评论 -->
    <div class="comment-form">
      <el-input
        v-model="commentForm.content"
        type="textarea"
        :rows="4"
        placeholder="请输入您的评论...（支持Markdown语法）"
        maxlength="1000"
        show-word-limit
        resize="none"
      />
      <div class="form-actions">
        <el-button 
          type="primary" 
          @click="submitComment"
          :disabled="!commentForm.content.trim()"
          :loading="loading"
        >
          发表评论
        </el-button>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list" v-loading="loading">
      <div 
        v-for="comment in commentList" 
        :key="comment.id" 
        class="comment-item"
      >
        <!-- 主评论 -->
        <div class="comment-main">
          <div class="comment-avatar">
            <el-avatar 
              :src="comment.author?.avatar" 
              :size="44"
              class="avatar"
            >
              {{ comment.author?.nickname?.charAt(0) || comment.author?.username?.charAt(0) || '?' }}
            </el-avatar>
          </div>
          <div class="comment-content">
            <div class="comment-header-info">
              <div class="author-info">
                <span class="comment-author-name">
                  {{ comment.author?.nickname || comment.author?.username || '未知用户' }}
                </span>
                <span class="comment-time">{{ formatTime(comment.createdAt) }}</span>
              </div>
              <div class="comment-actions">
                <el-button 
                  link 
                  type="primary" 
                  :icon="ChatDotRound"
                  @click="toggleReply(comment.id)"
                  class="action-btn"
                >
                  回复
                </el-button>
                <el-button 
                  link 
                  :icon="Star"
                  @click="handleLikeComment(comment)"
                  class="action-btn"
                >
                  点赞 ({{ comment.likes || 0 }})
                </el-button>
                <el-button 
                  v-if="canDeleteComment(comment)" 
                  link 
                  type="danger" 
                  :icon="Delete"
                  @click="handleDeleteComment(comment)"
                  class="action-btn delete-btn"
                >
                  删除
                </el-button>
              </div>
            </div>
            
            <div class="comment-text">{{ comment.content }}</div>

            <!-- 回复框 -->
            <div 
              v-if="replyStates[comment.id]?.visible" 
              :id="`reply-form-${comment.id}`"
              class="reply-form"
            >
              <el-input
                v-model="replyStates[comment.id].content"
                type="textarea"
                :rows="3"
                placeholder="请输入回复..."
                maxlength="1000"
                show-word-limit
                resize="none"
              />
              <div class="reply-actions">
                <el-button 
                  size="small" 
                  @click="toggleReply(comment.id)"
                >
                  取消
                </el-button>
                <el-button 
                  type="primary" 
                  size="small" 
                  :loading="replyStates[comment.id].loading"
                  @click="submitReply(comment.id)"
                  :disabled="!replyStates[comment.id].content.trim()"
                >
                  回复
                </el-button>
              </div>
            </div>

            <!-- 回复列表 -->
            <div v-if="comment.replies && comment.replies.length > 0" class="reply-list">
              <div 
                v-for="reply in comment.replies" 
                :key="reply.id" 
                class="reply-item"
              >
                <div class="reply-avatar">
                  <el-avatar 
                    :src="reply.author?.avatar" 
                    :size="36"
                    class="avatar"
                  >
                    {{ reply.author?.nickname?.charAt(0) || reply.author?.username?.charAt(0) || '?' }}
                  </el-avatar>
                </div>
                <div class="reply-content">
                  <div class="reply-header-info">
                    <div class="author-info">
                      <span class="reply-author-name">
                        {{ reply.author?.nickname || reply.author?.username || '未知用户' }}
                      </span>
                      <span class="reply-time">{{ formatTime(reply.createdAt) }}</span>
                    </div>
                    <div class="reply-actions">
                      <el-button 
                        link 
                        :icon="Star"
                        @click="handleLikeComment(reply)"
                        class="action-btn"
                      >
                        点赞 ({{ reply.likes || 0 }})
                      </el-button>
                      <el-button 
                        v-if="canDeleteComment(reply)" 
                        link 
                        type="danger" 
                        :icon="Delete"
                        @click="handleDeleteComment(reply)"
                        class="action-btn delete-btn"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                  <div class="reply-text">{{ reply.content }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && commentList.length === 0" class="empty-comments">
        <el-empty description="暂无评论" :image-size="100" />
        <p class="empty-tip">快来发表第一条评论吧！</p>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.total > 0" class="comment-pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped>
.comment-section {
  margin-top: 30px;
}

.comment-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.comment-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.comment-form {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.form-actions {
  margin-top: 12px;
  text-align: right;
}

.comment-list {
  min-height: 200px;
}

.comment-item {
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-main {
  display: flex;
  gap: 16px;
}

.comment-avatar {
  flex-shrink: 0;
}

.avatar {
  border: 2px solid #e8e8e8;
}

.comment-content {
  flex: 1;
  min-width: 0;
}

.comment-header-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 8px;
}

.author-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.comment-author-name {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.comment-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}

.action-btn {
  padding: 4px 8px;
  height: auto;
  font-size: 12px;
}

.delete-btn {
  color: #f56c6c;
}

.comment-text {
  color: #333;
  line-height: 1.6;
  font-size: 14px;
  margin-bottom: 12px;
  white-space: pre-wrap;
  word-break: break-word;
}

.reply-form {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.reply-actions {
  margin-top: 8px;
  text-align: right;
}

.reply-list {
  margin-top: 16px;
  padding-left: 20px;
  border-left: 3px solid #e8e8e8;
}

.reply-item {
  margin-top: 16px;
  display: flex;
  gap: 12px;
}

.reply-avatar {
  flex-shrink: 0;
}

.reply-content {
  flex: 1;
  min-width: 0;
}

.reply-header-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 4px;
  flex-wrap: wrap;
  gap: 4px;
}

.reply-author-name {
  font-weight: 500;
  color: #666;
  font-size: 13px;
}

.reply-time {
  color: #999;
  font-size: 11px;
}

.reply-text {
  color: #666;
  line-height: 1.5;
  font-size: 13px;
  white-space: pre-wrap;
  word-break: break-word;
}

.empty-comments {
  text-align: center;
  padding: 40px 20px;
}

.empty-tip {
  margin-top: 8px;
  color: #999;
  font-size: 14px;
}

.comment-pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comment-main {
    flex-direction: column;
    gap: 12px;
  }
  
  .comment-avatar {
    align-self: flex-start;
  }
  
  .comment-header-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .comment-actions {
    align-self: flex-start;
  }
  
  .reply-list {
    padding-left: 12px;
  }
  
  .reply-item {
    flex-direction: column;
    gap: 8px;
  }
  
  .reply-header-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .comment-form {
    padding: 16px;
  }
}
</style>